<template>
  <a-drawer v-model:visible="vdata.visible" :title="'生成二维码'" placement="right" width="600" :mask-closable="false">
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="单个卷码生成">
        <a-form
          ref="infoFormModel"
          :model="vdata.saveObject"
          layout="vertical"
          :rules="rules"
          style="padding-bottom:50px"
        >
          <a-row justify="space-between" type="flex">
            <a-col :span="10">
              <a-form-item>
                <template #label>
                  本活动还可发放 &nbsp;<strong>{{ couponNum(vdata.activityAwardList) }}</strong> &nbsp;次
                </template>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="微信小程序" name="appId" :wrapper-col="{ span: 10 }">
                <a-select v-model:value="vdata.saveObject['appId']" :options="officialList" placeholder="请选择微信小程序" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="tag类型" name="tagType">
                <a-radio-group v-model:value="vdata.saveObject['tagType']">
                  <a-radio :value="0">商户</a-radio>
                  <a-radio :value="1">机构网点</a-radio>
                  <a-radio :value="2">客户经理</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col v-if="vdata.saveObject.tagType !== 2" :span="24">
              <a-form-item label="tag内容" name="tagInfo">
                <a-textarea v-model:value="vdata.saveObject['tagInfo']" placeholder="请输入tag内容" :rows="4" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item v-if="vdata.saveObject.tagType==2" label="机构" name="agentNo">
                <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" :isNeedDefault="false" :agentNo="vdata.saveObject.agentNo" />
              </a-form-item>
            </a-col>
            <a-col v-if="vdata.saveObject.tagType == 2" :span="10">
              <a-form-item label="tag内容" name="tagInfo">
                <a-select v-model:value="vdata.saveObject['tagInfo']" :options="employeeList" placeholder="请选择tag内容" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="生成二维码类型" name="type">
                <a-radio-group v-model:value="vdata.saveObject['type']">
                  <a-radio :value="0">无限次使用二维码</a-radio>
                  <a-radio :value="1">固定次使用二维码</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <template v-if="vdata.saveObject['type'] === 1">
              <a-col :span="24">
                <a-form-item label="单客户可领" name="numEveryone">
                  <a-input-number
                    v-model:value="vdata.saveObject['numEveryone']"
                    :min="-1"
                    :max="couponNum(vdata.activityAwardList)"
                  />&nbsp;次
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="总共可领" name="numTotal">
                  <a-input-number
                    v-model:value="vdata.saveObject['numTotal']"
                    :min="vdata.saveObject['numEveryone'] || -1"
                    :max="couponNum(vdata.activityAwardList)"
                  />&nbsp;次
                </a-form-item>
              </a-col>
            </template>
          </a-row>

          <!-- 列表展示 -->
          <GzTable
            ref="infoTableRef"
            :table-columns="tableColumns"
            :pagination="true"
            :scrollX="0"
            :dataSource="resultList"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'operation'">
                <a-button danger @click="activityDelete(record)">删除</a-button>
              </template>
            </template>
          </GzTable>

          <div class="drawer-btn-center">
            <a-button :style="{ marginRight: '8px' }" @click="onClose">
              <close-outlined />
              取消
            </a-button>
            <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
              <check-outlined />
              保存
            </a-button>
          </div>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="多个卷码生成" force-render style="height: 100%;">
        <a-form-item label="微信小程序" name="appId" :wrapper-col="{ span: 10 }">
          <a-select v-model:value="vdata.saveObject['appId']" :options="officialList" placeholder="请选择微信小程序" />
        </a-form-item>
        <span style="margin-right: 40px;">文件上传</span>
        <a-button
          class="item"
          type="link"
          style="padding: 4px 0"
          @click="exportToExcel('领券码模板', ['团长商户号', '单客户可领', '配券张数'], [])"
        >
          领券码模板下载
        </a-button>
        <a-upload-dragger
          v-model:fileList="vdata.saveObject['fileList']"
          :action="vdata['action']"
          :data="vdata.formParams"
          :maxCount="1"
          accept=".xlsx, .xls"
          name="file"
          :beforeUpload="beforeUpload"
          @change="uploadChange"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
          <p class="ant-upload-hint">
            <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
          </p>
        </a-upload-dragger>
        <!-- 列表展示 -->
        <GzTable
          ref="infoTableRef"
          :table-columns="tableColumns"
          :pagination="true"
          :scrollX="0"
          :dataSource="resultList"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <a-button danger @click="activityDelete(record)">删除</a-button>
            </template>
          </template>
        </GzTable>
      </a-tab-pane>
    </a-tabs>
  </a-drawer>
</template>

<script setup lang="ts">
import { req, API_URL_ACTIVITY_DETAILS,API_URL_ACTIVITY_CHANNEL_GETMCHLIST, API_URL_ACTIVITY_QRCODE, API_URL_QR_CODE, $getUploadFormParams, API_URL_QRCODERECORD_BATCHCREATEQRCODE, API_URL_QRCODERECORD_DELETEQRCODE } from '@/api/manage'

import { $getAgentWxListForActivity } from '@/api/activityManage/activityCreate/index'
import { ref, reactive, defineExpose, computed, getCurrentInstance,watch } from 'vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { exportToExcel } from '@/utils/excelUtils'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const activeKey = ref('1')
const infoFormModel = ref()
const vdata = reactive({
  visible: false, // 是否显示抽屉
  btnLoading: false, // 按钮loading
  activityAwardList: [],  // 活动奖品列表
  saveObject: { // 保存的对象
    action: '', //上传地址
    formParams: {},
    fileList: [], //上传文件列表
    activityId: null, // 活动id
    pathUrl: null, // 跳转的营销小程序路径 
    type: 0,
    tagType: 0,
  },
}) as any

// 表单校验规则
const rules = {
  tagType: [
    { required: true, message: '请选择tag类型', trigger: 'change' },
  ],
  tagInfo: [
    { required: true, message: '请输入tag内容', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择生成二维码类型', trigger: 'change' },
  ],
  numEveryone: [
    { required: true, message: '请输入单客户可领数量', trigger: 'change' },
  ],
  numTotal: [
    { required: true, message: '请输入总共可领数量', trigger: 'change' },
  ],
  appId: [
    { required: true, message: '请选择微信小程序', trigger: 'change' },
  ],
  agentNo: [
    { required: true, message: '请选择机构', trigger: 'change' },
  ],
}

const resultList = ref([])
// 列表表头
const tableColumns = [
  { key: 'tagInfo', title: '商户号', dataIndex: 'tagInfo' },
  { key: 'numTotal', title: '总数量', dataIndex: 'numTotal' },
  { key: 'numConsume', title: '已领数量', dataIndex: 'numConsume' },
  { key: 'operation', title: '操作', dataIndex: 'operation' },
]


function getQRcodeList() {
  req.list(API_URL_QR_CODE, { activityId: vdata.saveObject.activityId }).then(res => {        
    resultList.value = res
  })
}

const employeeList = ref([])
// 获取机构下面的客户经理
async function getMchListApi(agentNo:any) {
  const res = await req.add(API_URL_ACTIVITY_CHANNEL_GETMCHLIST, { agentNo: agentNo })
  employeeList.value =  res.map(item => ({ label: item.employeeName, value: item.agentEmployeeId }))
}


// 生成的二维码 跳转的营销小程序路径
const PATH_URL = 'pages/welcome/index'
/**
 * 保存
 */
const handleOkFunc = () => {
  infoFormModel.value.validate().then(() => {
    req.add(API_URL_ACTIVITY_QRCODE, vdata.saveObject).then(() => {
      $infoBox.message.success('生成成功')
      vdata.visible = false
    })
  }).catch(() => { })

}
/**
 * 打开抽屉
 */
const show = async (activityId, agentNo) => {
  // 数据初始化
  vdata.saveObject = {
    activityId,
    pathUrl: PATH_URL,
    tagType: 0,
    type: 0,
    appId: null,
    agentNo: agentNo || null,
  }
  const { activityAwardList } = await req.list(API_URL_ACTIVITY_DETAILS, { activityId, activityTemplateNo: 'ACTE004' })
  // 根据活动列表计算卡券总数 以及还可派发数量
  vdata.activityAwardList = activityAwardList
  vdata.visible = true
  getQRcodeList()
  getAgentWxList(agentNo)
}
// 卡券已派发数量
const couponGet = computed(() => {
  return (couponList) => {
    if (couponList && couponList.length) {
      return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.awardGet, 0)
    } else {
      return 0
    }
  }
})
// 卡券还可派发数量
const couponNum = computed(() => {
  return (couponList) => {
    if (couponList && couponList.length) {
      return couponList[0].awardNum - couponList[0].awardGet
    } else {
      return 0
    }
  }
})


/**
 * 文件上传
 */
function beforeUpload(file) {
  if (!vdata.saveObject.appId) {
    $infoBox.message.warn('请选择小程序！')
    return false
  }
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then(res => {
    vdata.action = res.formActionUrl // action 
    vdata.formParams = res.formParams //表单组件 
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}

function complete() {
  req
    .add(API_URL_QRCODERECORD_BATCHCREATEQRCODE, vdata.saveObject)
    .then((res) => {
      $infoBox.message.success('生成成功')
      vdata.visible = false
      // getQRcodeList()
    })
}
function uploadChange(info) {
  if (info.file.status === 'error') { // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  } if (info.file.status === 'done') {
    // 上传成功
    complete()
  }
}

function activityDelete(record: any) {
  $infoBox.confirmDanger('确认删除？', '请确认是否删除当前商户？', () => {
    req.delById(API_URL_QRCODERECORD_DELETEQRCODE, record.qrcodeRecordId).then(() => {
      $infoBox.message.success('删除成功！')
      getQRcodeList()
    })
  })


}
/**
 * 关闭抽屉
 */
const onClose = () => {
  vdata.visible = false
}
// 查询机构小程序/公众号列表接口  0微信公众号   1微信小程序 
const officialList = ref([])
async function getAgentWxList(agentNo) {
  const res = await $getAgentWxListForActivity({ agentNo, type: 1})
  officialList.value = res.map(item => ({ label: item.name, value: item.appId }))
}
 watch(() => vdata.saveObject.agentNo, (newVal) => {
  if (newVal) {
    // 选择机构后，获取该机构下的客户经理列表
    vdata.saveObject.tagInfo = null // 清空tag内容
    getMchListApi(newVal)
  } else {
    employeeList.value = []
  }
}, { immediate: true })
// 暴露属性
defineExpose({ show })
</script>
<style scoped lang="less">
/deep/ .ant-upload-list-item-name {
  width: auto;
  flex-grow: 1 !important;
}
</style>